﻿using Lgc_Shop.Models;
using Lgc_Shop.Models.Database;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Xml.Linq;
using WebAPI_Demo.Service;

namespace Lgc_Shop.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        // 定义数据库上下文
        private readonly Lgc_ShopContext _db;
        private readonly IJWTService _jwtService;

        /// <summary>
        /// 构造方法 构造注入
        /// 把数据库上下文初始化
        /// </summary>
        /// <param name="db"></param>
        public UserController(Lgc_ShopContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public string Register(User_Register user)
        {
            var newUser = new User
            {
                Tel = user.Tel,
                Password = user.Password,
                Createtime = System.DateTime.Now
            };

            var row = _db.Users.Count(x => x.Tel == user.Tel);
            if (row > 0)
            {
                return "该手机号已注册";
            }
            _db.Users.Add(newUser);
            return _db.SaveChanges() > 0 ? "注册成功" : "注册失败";
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="tel">请输入手机号</param>
        /// <param name="pwd">请输入密码</param>
        /// <returns></returns>
        [HttpGet]
        public string Login(string tel,string pwd)
        {
            var row = _db.Users.Count(x => x.Tel == tel && x.Password == pwd);
            if(row > 0)
            {
                var userid = _db.Users.FirstOrDefault(x => x.Tel == tel).Id;
                return "您的token：" + _jwtService.CreateToken(tel, userid);
            }
            else
            {
                return "账号或密码错误";
            }
        }

        /// <summary>
        /// 个人中心
        /// </summary>
        [HttpGet]
        [Authorize]//标签 接口需要授权
        public List<string> ShowUser()
        {
            //获取用户信息           登录用户 消息载荷 查询第一条（条件是Type==）   获取登录用户的用户名
            var userTel = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value; // 获取登录用户的手机号
            // 获取用户的头像
            var userPhoto = _db.Users.FirstOrDefault(x => x.Tel == userTel).Photo;
            // 获取用户的昵称
            var userName = _db.Users.FirstOrDefault(x => x.Tel == userTel).Name;
            // 获取用户注册时间，, '2024-04-28 00:00:00.000'，只取2024-04-28 00:00:00
            var userTime = _db.Users.FirstOrDefault(x => x.Tel == userTel).Createtime.ToString().Split('.')[0];
            // 查询用户各订单状态的数量
            var orderCount_No = _db.Orders.Where(x => x.OrderUser == userTel && x.OrderState == "待发货").Select(x => x.OrderNo).Distinct().Count();
            var orderCount_Yes = _db.Orders.Where(x => x.OrderUser == userTel && x.OrderState == "已发货").Select(x => x.OrderNo).Distinct().Count();
            var orderCount_All = _db.Orders.Where(x => x.OrderUser == userTel).Select(x => x.OrderNo).Distinct().Count();

            if (userName == null)
            {
                userName = userTel;
            }

            //新建一个列表，用于存储用户的个人信息，并返回
            List<string> list = new List<string>();
            list.Add("用户头像：" + userPhoto);
            list.Add("用户昵称：" + userName);
            list.Add("注册时间：" + userTime.ToString());
            list.Add("全部订单数量：" + orderCount_All.ToString());
            list.Add("待发货：" + orderCount_No.ToString());
            list.Add("已发货：" + orderCount_Yes.ToString());
            return list;
        }

        /// <summary>
        /// 用户信息修改
        /// </summary>
        /// <param name="photo">请输入新的头像地址</param>
        /// <param name="name">请输入新的昵称</param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]//标签 接口需要授权
        public string UpdateUser(string photo,string name)
        {
            //获取用户信息           登录用户 消息载荷 查询第一条（条件是Type==）   获取登录用户的用户名
            var userTel = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value; // 获取登录用户的手机号
            _db.Users.FirstOrDefault(x => x.Tel == userTel).Photo = photo;
            _db.Users.FirstOrDefault(x => x.Tel == userTel).Name = name;
            var row = _db.SaveChanges();
            if(row > 0)
            {
                return "修改成功";
            }
            else
            {
                return "修改失败";
            }
        }
    }
}
